package xyz.missou.blog.controller;
/*
 * 图片上传Controller
 * */

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import xyz.missou.blog.utils.QiniuPictureUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class PictureController {

    @Value("${qiniu.accessKey}")
    private String accessKey;
    @Value("${qiniu.secretKey}")
    private String secretKey;
    @Value("${qiniu.bucket}")
    private String bucket;
    @Value("${qiniu.baseUrl}")
    private String baseUrl;

    @ResponseBody
    @RequestMapping({"/pic/upload/","/pic/upload"})
    public Map uploadImage(@RequestParam("editormd-image-file") MultipartFile uploadImage){
        String url;
        Map result=null;
        try {
            //设置上传参数
            QiniuPictureUtil.setAccessKey(accessKey);
            QiniuPictureUtil.setSecretKey(secretKey);
            QiniuPictureUtil.setBucket(bucket);
            QiniuPictureUtil.setBaseUrl(baseUrl);
            //上传图片
            //得到图片地址和文件名
            url=QiniuPictureUtil.uploadPicture(uploadImage.getOriginalFilename(), uploadImage.getBytes());
            result=new HashMap();
            result.put("success",1);
            result.put("message","图片上传成功");
            result.put("url",url);
            //返回文件信息
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            result=new HashMap();
            result.put("success",0);
            result.put("message","图片上传失败");
            result.put("url",null);
            //返回文件信息
            return result;
        }
    }

}
